/*
 *   Licensed to the Apache Software Foundation (ASF) under one
 *   or more contributor license agreements.  See the NOTICE file
 *   distributed with this work for additional information
 *   regarding copyright ownership.  The ASF licenses this file
 *   to you under the Apache License, Version 2.0 (the
 *   "License"); you may not use this file except in compliance
 *   with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing,
 *   software distributed under the License is distributed on an
 *   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *   KIND, either express or implied.  See the License for the
 *   specific language governing permissions and limitations
 *   under the License.
 *
 */

package org.apache.directory.http.client.data.model;


import java.util.ArrayList;
import java.util.List;

import org.apache.directory.http.client.LdapHttpConnection;
import org.apache.directory.shared.ldap.constants.SchemaConstants;
import org.apache.directory.shared.ldap.cursor.Cursor;
import org.apache.directory.shared.ldap.entry.Entry;
import org.apache.directory.shared.ldap.filter.SearchScope;
import org.apache.directory.shared.ldap.message.Response;
import org.apache.directory.shared.ldap.message.SearchResultEntry;


/**
 * TODO EntryLoader.
 *
 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
 */
public class ConfigDataLoader
{
    private LdapHttpConnection connection;

    private static final String CONFIG_BASE = "ou=config";


    public ConfigDataLoader( LdapHttpConnection connection )
    {
        if ( !connection.isAuthenticated() )
        {
            throw new IllegalArgumentException( "connection is not authenticated" );
        }

        this.connection = connection;
    }


    public List<EntryData> getPartitions()
    {
        return null;
    }


    public EntryData getDirService() throws Exception
    {
        return getData( CONFIG_BASE, "(ads-directoryServiceId=*)", SearchScope.ONELEVEL ).get( 0 );
    }


    public List<EntryData> getInterceptors() throws Exception
    {
        EntryData dirService = getDirService();

        return getData( dirService.getDn().getName(), "(ads-interceptorId=*)", SearchScope.SUBTREE );
    }


    private List<EntryData> getData( String baseDn, String filter, SearchScope scope ) throws Exception
    {
        List<EntryData> data = new ArrayList<EntryData>();

        Cursor<Response> cursor = connection.search( baseDn, filter, scope, SchemaConstants.ALL_USER_ATTRIBUTES,
            SchemaConstants.ALL_OPERATIONAL_ATTRIBUTES );
        while ( cursor.next() )
        {
            Entry entry = ( ( SearchResultEntry ) cursor.get() ).getEntry();
            data.add( new EntryData( entry ) );
        }

        cursor.close();

        return data;
    }
}
